<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title th:text="${category != null ? '编辑分类' : '新增分类'} + ' - 后台管理'"></title>
    <header th:replace="back/header::headerFragment('分类管理','category')"></header>
</head>
<body>
<div id="wrapper">
    <!-- 引入导航栏 -->
    <div th:replace="back/header::header-body"></div>

    <div id="page-wrapper">
        <div class="container-fluid">
            <!-- Page Heading -->
            <div class="row">
                <div class="col-lg-12">
                    <h1 class="page-header" th:text="${category != null ? '编辑分类' : '新增分类'}"></h1>
                    <ol class="breadcrumb">
                        <li><i class="fa fa-dashboard"></i> <a th:href="@{/admin}">仪表盘</a></li>
                        <li><i class="fa fa-tags"></i> <a th:href="@{/admin/category}">分类列表</a></li>
                        <li class="active" th:text="${category != null ? '编辑' : '新增'}"></li>
                    </ol>
                </div>
            </div>
            <!-- /.row -->

            <div class="row">
                <div class="col-lg-6">
                    <form id="categoryForm" role="form">
                        <input type="hidden" name="id" th:if="${category != null}" th:value="${category.id}">
                        <div class="form-group">
                            <label for="categoryName">分类名称</label>
                            <input type="text" class="form-control" id="categoryName" name="name"
                                   placeholder="请输入分类名称" th:value="${category != null ? category.name : ''}" required>
                        </div>
                        <button type="button" onclick="submitCategory()" class="btn btn-success">保存</button>
                        <a th:href="@{/admin/category}" class="btn btn-default">返回列表</a>
                    </form>
                </div>
            </div>
            <!-- /.row -->
        </div>
        <!-- /.container-fluid -->
    </div>
    <!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->

<div th:replace="back/footer.html"></div>

<script type="text/javascript">
    function submitCategory() {
        var categoryName = $('#categoryName').val();
        if (!categoryName || categoryName.trim() === '') {
            alert('分类名称不能为空！');
            return;
        }

        $.ajax({
            url: '/admin/category/save',
            type: 'POST',
            data: $('#categoryForm').serialize(),
            success: function(response) {
                if (response.code === 1) {
                    alert('保存成功！');
                    window.location.href = '/admin/category';
                } else {
                    alert('保存失败：' + response.msg);
                }
            },
            error: function() {
                alert('请求失败，请稍后重试。');
            }
        });
    }
</script>

</body>
</html>